<template>
  <!-- 项目录入 -->
  <el-dialog
    v-model="props.visible"
    width="800px"
    :show-close="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          {{ dialogTitle }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>

    <div
      class="main"
      v-if="store.category !== null"
    >
      <el-form
        ref="formEl"
        :model="formData"
        :rules="rules"
        label-width="130px"
        status-icon
      >
        <el-form-item
          v-if="secondLevelOptions.length > 1"
          :label="mediumLabel"
          prop="mediumId"
        >
          <el-radio-group
            v-model="formData.mediumId"
            @change="changeMedium"
          >
            <el-radio
              v-for="item in secondLevelOptions"
              :key="item.outsourcingProjectId"
              :label="item.outsourcingProjectId"
            >
              {{ item.projectName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="projectLabel"
          prop="outsourcingProjectId"
        >
          <el-radio-group v-model="formData.outsourcingProjectId">
            <el-radio
              v-for="item in threeLevelOptions"
              :key="item.outsourcingProjectId"
              :label="item.outsourcingProjectId"
            >
              {{ item.projectName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="store.category.projectNameCn === '航修'">
          <!-- 项目名称 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l1')"
            prop="assistName"
          >
            <el-input
              v-model.trim="formData.assistName"
              :placeholder="t('externalAssistance.ProjectAdd.p1')"
              :maxlength="50"
            />
          </el-form-item>
          <!-- 规格型号 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l2')"
            prop="assistSpec"
          >
            <div class="grid">
              <el-input
                v-model.trim="formData.assistSpec"
                :placeholder="t('externalAssistance.ProjectAdd.p2-1')"
                :maxlength="50"
              />
              <el-input
                v-model.trim="formData.assistModel"
                :placeholder="t('externalAssistance.ProjectAdd.p2-2')"
                :maxlength="50"
              />
            </div>
          </el-form-item>
          <!-- 船级社 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l3')"
            prop="classificationSociety"
          >
            <el-input
              v-model.trim="formData.classificationSociety"
              :placeholder="t('externalAssistance.ProjectAdd.p3')"
              :maxlength="50"
            />
          </el-form-item>
          <!-- 外协项目数量 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l4')"
            prop="requireCount"
          >
            <div class="grid">
              <el-input-number
                v-model="formData.requireCount"
                :placeholder="t('externalAssistance.ProjectAdd.p4-1')"
                :controls="false"
                style="width: 100%"
                :max="999999999"
              />
              <el-input
                v-model.trim="formData.unit"
                :placeholder="t('externalAssistance.ProjectAdd.p4-2')"
                :maxlength="50"
              />
            </div>
          </el-form-item>
          <!-- 施工位置 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l5')"
            prop="constructionLocation"
          >
            <el-radio-group v-model="formData.constructionLocation">
              <el-radio
                v-for="item in dictData.construction_location"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 外协项目备注 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l6')"
            prop="remark"
          >
            <el-input
              v-model.trim="formData.remark"
              type="textarea"
              :placeholder="t('externalAssistance.ProjectAdd.p6')"
              :maxlength="100"
            />
          </el-form-item>
          <!-- 要求完工时长 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l7')"
            prop="completionTime"
          >
            <el-input-number
              v-model="formData.completionTime"
              :placeholder="t('externalAssistance.ProjectAdd.p7')"
              :min="0"
              :controls="false"
              style="width: 100%"
              :max="999999999"
            />
          </el-form-item>
        </template>

        <!--  -->
        <template v-if="store.category.projectNameCn === '外协'">
          <!-- 项目名称 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l1')"
            prop="assistName"
          >
            <el-input
              v-model.trim="formData.assistName"
              :placeholder="t('externalAssistance.ProjectAdd.p1')"
              :maxlength="50"
            />
          </el-form-item>
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l6')"
            prop="remark"
          >
            <el-input
              v-model.trim="formData.remark"
              type="textarea"
              :placeholder="t('externalAssistance.ProjectAdd.p6')"
              :maxlength="100"
            />
          </el-form-item>
        </template>

        <!--  -->
        <template v-if="store.category.projectNameCn === '技术服务'">
          <!-- 服务名称 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l8')"
            prop="assistName"
          >
            <el-input
              v-model.trim="formData.assistName"
              :placeholder="t('externalAssistance.ProjectAdd.p8')"
              :maxlength="50"
            />
          </el-form-item>
          <!-- 规格型号 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l2')"
            prop="assistSpec"
          >
            <div class="grid">
              <el-input
                v-model.trim="formData.assistSpec"
                :placeholder="t('externalAssistance.ProjectAdd.p2-1')"
                :maxlength="50"
              />
              <el-input
                v-model.trim="formData.assistModel"
                :placeholder="t('externalAssistance.ProjectAdd.p2-2')"
                :maxlength="50"
              />
            </div>
          </el-form-item>
          <!-- 船级社 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l3')"
            prop="classificationSociety"
          >
            <el-input
              v-model.trim="formData.classificationSociety"
              :placeholder="t('externalAssistance.ProjectAdd.p3')"
              :maxlength="50"
            />
          </el-form-item>
          <!-- 外协项目数量 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l4')"
            prop="requireCount"
          >
            <div class="grid">
              <el-input-number
                v-model="formData.requireCount"
                :placeholder="t('externalAssistance.ProjectAdd.p4-1')"
                :controls="false"
                style="width: 100%"
                :max="999999999"
              />
              <el-input
                v-model.trim="formData.unit"
                :placeholder="t('externalAssistance.ProjectAdd.p4-2')"
                :maxlength="50"
              />
            </div>
          </el-form-item>
          <!-- 外协项目备注 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l6')"
            prop="remark"
          >
            <el-input
              v-model.trim="formData.remark"
              type="textarea"
              :placeholder="t('externalAssistance.ProjectAdd.p6')"
              :maxlength="100"
            />
          </el-form-item>
        </template>

        <!--  -->
        <template v-if="store.category.projectNameCn === '代理&报关'">
          <!-- 代理地点 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l9')"
            prop="agentLocation"
          >
            <el-input
              v-model.trim="formData.agentLocation"
              :placeholder="t('externalAssistance.ProjectAdd.p9')"
              :maxlength="50"
            />
          </el-form-item>
          <!-- 靠泊时间 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l10')"
            prop="berthingBeginTime"
          >
            <el-date-picker
              v-model="dateTime.berthingBeginTime"
              type="daterange"
              range-separator="To"
              :start-placeholder="t('externalAssistance.ProjectAdd.l10_1')"
              end-placeholder="t('externalAssistance.ProjectAdd.l10_2')"
              @change="dateChange($event, 'berthingBeginTime', 'berthingEndTime')"
            />
          </el-form-item>
          <!-- 外协项目备注 -->
          <el-form-item
            :label="t('externalAssistance.ProjectAdd.l6')"
            prop="remark"
          >
            <el-input
              v-model.trim="formData.remark"
              type="textarea"
              :placeholder="t('externalAssistance.ProjectAdd.p6')"
              :maxlength="100"
            />
          </el-form-item>
        </template>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer flexcc">
        <el-button
          color="#252628"
          plain
          @click="cancel"
        >
          {{ t('cancelText') }}
        </el-button>
        <el-button
          v-if="!editRow"
          color="#252628"
          plain
          @click="confirm(true)"
        >
          <!-- 新增一个 -->
          {{ t('externalAssistance.ProjectAdd.newAddOne') }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="confirm(false)"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useExternalAssistance from '@/stores/externalAssistance.js'
import { editOrderDetailApi } from '@/service/externalAssistance'
import { cloneDeep } from 'lodash'
import useDict from '@/hooks/useDict'
const { dictData, getDictData } = useDict()

const { t, locale } = useI18n()

const router = useRouter()
const route = useRoute()

const store = useExternalAssistance()

onBeforeMount(() => {
  getDictData('construction_location')
})

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editRow: {
    type: Object,
    default: () => null
  },
  checkedRow: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['close', 'getDetail'])

// title
const dialogTitle = computed(() => {
  const obj = {
    航修: t('externalAssistance.ProjectAdd.t1'),
    外协: t('externalAssistance.ProjectAdd.t2'),
    技术服务: t('externalAssistance.ProjectAdd.t3'),
    '代理&报关': t('externalAssistance.ProjectAdd.t4')
  }
  return obj[store.category.projectNameCn]
})
const mediumLabel = computed(() => {
  const obj = {
    航修: '',
    外协: '',
    技术服务: t('externalAssistance.ProjectAdd.l11'),
    '代理&报关': ''
  }
  return obj[store.category.projectNameCn]
})
const projectLabel = computed(() => {
  const obj = {
    航修: t('externalAssistance.ProjectAdd.l12'),
    外协: t('externalAssistance.ProjectAdd.l13'),
    技术服务: t('externalAssistance.ProjectAdd.l14'),
    '代理&报关': t('externalAssistance.ProjectAdd.l15')
  }
  return obj[store.category.projectNameCn]
})

const handleClose = () => {
  emit('close')
}

const cancel = () => {
  handleClose()
}
const confirm = (isAddone = false) => {
  if (!formEl.value) return
  formEl.value.validate((valid, fields) => {
    if (valid) {
      const params = cloneDeep(formData.value)
      editOrderDetailApi(params).then(({ msg }) => {
        ElMessage.success(msg)

        if (isAddone) {
          formData.value = {
            ...formDataTmp,
            mediumId: params.mediumId,
            outsourcingProjectId: params.outsourcingProjectId
          }
        } else {
          handleClose()
        }

        emit('getDetail')
      })
    }
  })
}

// 二级类别
const secondLevelOptions = computed(() => {
  const res = store.categoryList.find((item) => item.outsourcingProjectId === store.category.outsourcingProjectId)?.outsourcingProjectWebVoList
  if (res.length === 1) {
    formData.value.mediumId = res[0].outsourcingProjectId
  }
  return res
})

// 三级类别
const threeLevelOptions = computed(() => {
  return secondLevelOptions.value.find((item) => item.outsourcingProjectId === formData.value.mediumId)?.outsourcingProjectWebVoList
})

// 选择二级时
const changeMedium = () => {
  if (formData.value.outsourcingProjectId) {
    formData.value.outsourcingProjectId = null
  }
}

const dateTime = ref({
  berthingTime: null
})
const dateChange = (val, s, e) => {
  if (val) {
    formData.value[s] = String(val[0]).substring(0, 10) * 1
    formData.value[e] = String(val[1]).substring(0, 10) * 1
  } else {
    formData.value[s] = null
    formData.value[e] = null
  }
}

// 表单
const formEl = ref(null)
const formDataTmp = {
  largeId: store.category.outsourcingProjectId, // 一级id
  assistOrderId: store.orderInfo.id // 外协单Id
}
const formData = ref(cloneDeep(formDataTmp))
if (props.editRow) {
  formData.value = { ...formData.value, ...props.editRow, completionTime: Number(props.editRow.completionTime) } // 回显
}
if (props.checkedRow) {
  formData.value.previousId = props.checkedRow.id // 上一级id
}
const validator = {
  berthingBeginTime: (rule, value, callback) => {
    if (!formData.value.berthingBeginTime || !formData.value.berthingEndTime) {
      return callback(new Error(t('externalAssistance.ProjectAdd.r6')))
    }
    callback()
  },
  requireCount: (rule, value, callback) => {
    if (!value) {
      return callback(new Error(t('externalAssistance.ProjectAdd.r4')))
    }
    if (!formData.value.unit && !['代理&报关'].includes(store.category.projectNameCn)) {
      return callback(new Error(t('externalAssistance.ProjectAdd.r4_1')))
    }

    callback()
  }
}
const rules = reactive({
  mediumId: [{ required: true, message: t('select_p'), trigger: 'change' }],
  outsourcingProjectId: [{ required: true, message: t('externalAssistance.ProjectAdd.r2'), trigger: 'change' }],
  classificationSociety: [{ required: true, message: t('externalAssistance.ProjectAdd.r3'), trigger: 'change' }],
  requireCount: [{ required: true, validator: validator.requireCount, trigger: 'change' }],
  completionTime: [{ required: true, message: t('externalAssistance.ProjectAdd.r5'), trigger: 'change' }],
  berthingBeginTime: [{ required: true, validator: validator.berthingBeginTime, trigger: 'change' }]
})
</script>

<style scoped lang="scss">
.main {
  padding: 0 50px;
}
.grid {
  display: grid;
  width: 100%;
  grid-template-columns: repeat(2, 49%);
  justify-content: space-between;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
